package com.yxx.controller.user;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.yxx.medicinecommon.result.ResponseResult;
import com.yxx.medicinepojo.vo.ChineseWesternMedicineVO;
import com.yxx.service.ChineseWesternMedicineService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yuxiangxun
 * @date 2024/9/23
 * @apiNote
 */
@RestController("userChineseWesternMedicineController")
@Slf4j
@RequestMapping("/user/chinesewesternmedicine")
@Api(tags = "小程序端 中/西药接口")
public class ChineseWesternMedicineController {

    @Autowired
    private ChineseWesternMedicineService chineseWesternMedicineService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("中/西药信息列表")
    public ResponseResult<List<ChineseWesternMedicineVO>> chinesesWesternMedicineList(Long medicinecategoryId){
        //创建ChineseWesternMedicineRedis的key  声明：xxx_ChineseWesternMedicine_medicinecategoryId  其中：xxx为Redis将key序列化的编号
        String UserChineseWesternMedicine_Key = "_User_ChineseWesternMedicine_" + medicinecategoryId;

        //先从redis中获取中西药的缓存数据信息，如果内存中有缓存中西药的数据，直接从redis中提取这些数据，否则先在数据库中获取到这些数据，再缓存到redis中
        List<ChineseWesternMedicineVO> chineseWesternMedicineVOList = (List<ChineseWesternMedicineVO>) redisTemplate.opsForValue().get(UserChineseWesternMedicine_Key);
        log.info("chineseWesternMedicineVOList:{}",chineseWesternMedicineVOList);

        if(ObjectUtil.isNotEmpty(chineseWesternMedicineVOList) && chineseWesternMedicineVOList.size() > 0){
            return ResponseResult.success(chineseWesternMedicineVOList);
        }

        List<ChineseWesternMedicineVO> list = chineseWesternMedicineService.listByMedicineCategoryId(medicinecategoryId);
        log.info("Not_Redis_chineseWesternMedicineVOList:{}",list);
        //将从数据库中查询出来的中西药数据缓存到redis中再返回结果
        redisTemplate.opsForValue().set(UserChineseWesternMedicine_Key,list,30, TimeUnit.MINUTES);
        return ResponseResult.success(list);
    }
}
